package lib.bone.admin.controller.nepu;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Validator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lib.bone.admin.anno.WebLog;
import lib.bone.admin.constant.MethodTypeConst;
import lib.bone.common.constant.ResponseCodeConst;
import lib.bone.common.core.domain.ResponseDTO;
import lib.bone.common.exception.BusinessException;
import lib.bone.oss.service.IFileService;
import lib.bone.system.module.iojob.domain.IOJob;
import lib.bone.system.module.iojob.domain.dto.IOJobQueryDTO;
import lib.bone.system.module.iojob.domain.dto.IOJobUpdateDTO;
import lib.bone.system.module.iojob.service.IOJobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("nepu")
@Api(tags = "导入导出Job")
public class IOJobController {

    @Autowired
    IOJobService ioJobService;

    @Autowired
    IFileService fileService;

    @GetMapping(value = "iojobs")
    @ApiOperation(value = "查询全部",notes = "")
    public ResponseDTO getAll(IOJobQueryDTO ioJobQueryDTO){

        Sort sort;
        if(ioJobQueryDTO.getOrder().equalsIgnoreCase("DESC")){
            sort = Sort.by(Sort.Direction.DESC, ioJobQueryDTO.getSortBy());
        }else {
            sort = Sort.by(Sort.Direction.ASC, ioJobQueryDTO.getSortBy());
        }

        // tips : 页码对应 - 1
        Pageable pageable = PageRequest.of(ioJobQueryDTO.getPageNum() - 1 , ioJobQueryDTO.getPageSize(), sort);

        IOJob ioJob = new IOJob();
        BeanUtil.copyProperties(ioJobQueryDTO,ioJob, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        Example<IOJob> example = Example.of(ioJob);

        return ResponseDTO.succData(ioJobService.getAll(pageable,example));
    }

    @GetMapping("iojobs/{iojobId}/file")
    @ApiOperation(value = "IOJob文件下载(stream)")
    public ResponseEntity<byte[]> downLoadById(@PathVariable("iojobId") String iojobId, HttpServletRequest request) {
        Optional<IOJob> ioJobOp = ioJobService.getById(iojobId);
        if (!ioJobOp.isPresent()) {
            throw new BusinessException(ResponseCodeConst.NOT_FOUND);
        }
        IOJob ioJob = ioJobOp.get();

        return fileService.fileDownload(ioJob.getFilePath(),ioJob.getFileName(),request);
    }

    @GetMapping("iojobs/{iojobId}/logs")
    @ApiOperation(value = "IOJob日志下载(stream)")
    public ResponseEntity<byte[]> downLoadLogById(@PathVariable("iojobId") String iojobId, HttpServletRequest request) {
        Optional<IOJob> ioJobOp = ioJobService.getById(iojobId);
        if (!ioJobOp.isPresent()) {
            throw new BusinessException(ResponseCodeConst.NOT_FOUND);
        }
        IOJob ioJob = ioJobOp.get();
        if (Validator.isEmpty(ioJob.getLogFilePath())){
            throw new BusinessException(ResponseCodeConst.SYSTEM_ERROR,"无日志文件");
        }
        return fileService.fileDownload(ioJob.getLogFilePath(),ioJob.getFileName()+"日志",request);
    }



    @GetMapping("iojobs/{id}")
    @ApiOperation(value = "查询单条记录",notes = "传入ID")
    public ResponseDTO getOne(@PathVariable("id") String id) {
        Optional<IOJob> ioJobOp = ioJobService.getById(id);
        if (!ioJobOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND, "ID:[" + id + "]对应的数据不存在");
        return ResponseDTO.succData(ioJobOp.get());
    }

    @WebLog(module = "bone-system",operate = MethodTypeConst.DELETE)
    @DeleteMapping("iojobs/{id}")
    @ApiOperation(value = "删除单条记录",notes = "传入ID")
    public ResponseDTO deleteOne(@PathVariable("id") String id){
        return ioJobService.deleteById(id);
    }

    @WebLog(module = "bone-system",operate = MethodTypeConst.UPDATE)
    @PutMapping("iojobs")
    @ApiOperation(value = "更新单条记录",notes = "")
    public ResponseDTO updateOne(@RequestBody @Validated IOJobUpdateDTO ioJobUpdateDTO){
        Optional<IOJob> ioJobOp = ioJobService.getById(ioJobUpdateDTO.getId());
        if (!ioJobOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        }
        IOJob ioJob = ioJobOp.get();
        BeanUtil.copyProperties(ioJobUpdateDTO,ioJob,CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        return ResponseDTO.succData(ioJobService.updateOne(ioJob));
    }

}
